package com.ycb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycb.common.Result;
import com.ycb.exception.CustomException;
import com.ycb.pojo.Category;
import com.ycb.mapper.CategoryMapper;
import com.ycb.pojo.Dish;
import com.ycb.pojo.Setmeal;
import com.ycb.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycb.service.IDishService;
import com.ycb.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author ycb
 * @since 2024-09-30
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private IDishService dishService;

    @Override
    public Result<String> removeIfNotChildren(Long id) {
        //查询是否存在dish
        long dishCount = dishService.findCountByCategoryId(id);
        if (dishCount > 0) {
            throw new CustomException("当前菜品还存在菜品对象");
        }
        //查询是否存在stemeal
        long setmealCount = setmealService.findCountByCategoryId(id);
        if (setmealCount > 0) {
            throw new CustomException("当前套餐还存在套餐对象");
        }
        this.removeById(id);
        return Result.success("删除成功");
    }

    @Override
    public List<Category> listByType(Integer type) {
        List<Category> list;
        if (type != null) {
            QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
            categoryQueryWrapper.eq("type", type);
            list = this.list(categoryQueryWrapper);
        } else {
            list = this.list();
        }
        if (list == null) {
            return new ArrayList<>();
        }
        return list;
    }
}
